package com.potenza.wxuser.controller;

import com.alibaba.fastjson.JSON;
import com.potenza.wxuser.model.UserInfo;
import com.potenza.wxuser.model.WeixinUser;
import com.potenza.wxuser.service.WxMiniService;
import com.ruoyi.common.core.web.domain.AjaxResult;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.util.Map;
import java.util.concurrent.*;

@RestController
@RequestMapping("/c/wxuser")
@CrossOrigin
public class WxMiniController {

    @Autowired
    RestTemplate restTemplate;

    @Value("${wx-mini.appid}")
    String appid;
    @Value("${wx-mini.secret}")
    String secret;

    @Autowired
    WxMiniService wxMiniService;

    @GetMapping("/onLogin")
    public AjaxResult wxminOnLogin(@RequestParam("code") String code) {
        //https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid={appid}&secret={secret}&js_code={code}&grant_type=authorization_code";
        ResponseEntity<String> entity = restTemplate.getForEntity(url, String.class, appid, secret, code);
        String body = entity.getBody();

        StringUtils.substringMatch(body, 0, "openid");
        Map obj = JSON.parseObject(body, Map.class);
        String openid = (String) obj.get("openid");
        //Integer errcode = (Integer)obj.get("errcode");
        //String errmsg = (String)obj.get("errmsg");

        if (openid == null || StringUtils.isEmpty(openid)) {
            return new AjaxResult(500, "未获取openid", "");

        } else {
            String session_key = (String) obj.get("session_key");
            String unionid = (String) obj.get("unionid");

            System.out.println(openid);
            System.out.println(session_key);
            System.out.println(unionid);
            //根据openid查询数据库是否包含该用户，没有新增用户，否则不作处理
            WeixinUser weixinUser = new WeixinUser();
            weixinUser.setOpenid(openid);
            weixinUser.setSessionKey(session_key);
            weixinUser.setUnionid(unionid);

            wxMiniService.save(weixinUser);

            return new AjaxResult(200, "Success", openid);
        }
    }

    @RequestMapping(value = "/userInfo/{openid}", method = RequestMethod.POST)
    public AjaxResult wxminUserInfo(@PathVariable("openid") String openid, @RequestBody String userInfo_json) {

        System.out.println(userInfo_json);
        Map obj = JSON.parseObject(userInfo_json, Map.class);
        UserInfo userInfo = JSON.parseObject(userInfo_json, UserInfo.class);

        //更新数据库
        WeixinUser weixinUser = wxMiniService.findByOpenid(openid);
        BeanUtils.copyProperties(userInfo, weixinUser);
        wxMiniService.update(weixinUser);
        return new AjaxResult(200, "更新成功", weixinUser);
    }


   /*@Autowired
    @Qualifier("asyncServiceExecutor")
    private Executor asyncServiceExecutor;*/

    @PostMapping("uploadFile")
    public AjaxResult uploadFile(MultipartFile file) throws ExecutionException, InterruptedException {
        //保存到本地临时目录

       /* asyncServiceExecutor.execute(()->{
            // 加水印
            //OSS 上传
            waterMarkAndOss("000");
        });*/
        System.out.println("上传线程:" + Thread.currentThread().getName());
        Future<String> future = wxMiniService.waterMarkAndOss("0000");

        String oss_url = future.get();//阻塞


        return new AjaxResult(200, "upload成功");
    }


}
